﻿///////////////////////////////////////////////////////////////////////////////
//
// This file is part of the BassDrop project
//   https://code.google.com/p/bass-drop/
//
//
// Creator:	Gergely Krajcsovszki (krajcsovszkig@hotmail.com)
// Date:	2014-04-13 13:05
//
//
// Copyright © 2013-2014. Gergely Krajcsovszki
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BassDrop.Core.Common.General.Threading
{
	/// <summary>
	/// Asynchronous, awaitable manual reset event implementation
	/// </summary>
	/// <remarks> From http://blogs.msdn.com/b/pfxteam/archive/2012/02/11/10266920.aspx </remarks>
	public class AsyncManualResetEvent
	{
		private volatile TaskCompletionSource<bool> m_tcs = new TaskCompletionSource<bool>();

		/// <summary>
		/// Use with await to wait asynchronously for this AsyncManualResetEvent to be Set
		/// </summary>
		/// <returns></returns>
		public Task WaitAsync()
		{
			return m_tcs.Task;
		}

		/// <summary>
		/// Sets the state of the event to signaled, allowing waiting threads to proceed. 
		/// </summary>
		public void Set()
		{
			var tcs = m_tcs;

			Task.Factory.StartNew(
				s => ((TaskCompletionSource<bool>) s).TrySetResult( true ),
				tcs,
				CancellationToken.None,
				TaskCreationOptions.PreferFairness,
				TaskScheduler.Default );

			tcs.Task.Wait();
		}

		/// <summary>
		/// Sets the state of the event to nonsignaled, causing threads to block.
		/// </summary>
		public void Reset()
		{
			while ( true )
			{
				var tcs = m_tcs;
				if ( !tcs.Task.IsCompleted
#pragma warning disable 0420
 || Interlocked.CompareExchange( ref m_tcs, new TaskCompletionSource<bool>(), tcs ) == tcs )
#pragma warning restore
				{
					return;
				}
			}
		}
	}
}
